package com.usian.wemedia.gateway.filters;

import com.usian.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Log4j2
public class AuthorizeFilter implements GlobalFilter, Ordered {
   @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        获取request和response镀锡
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
//        判断请求路径是否为 /log/in
        if (request.getURI().getPath().contains("/login/in")){
//            放行
            return chain.filter(exchange);
        }
        try {
//        获取请求头信息中的token
           String token=request.getHeaders().getFirst("token");
//       校验token是否存在
          if (StringUtils.isEmpty(token)){
              response.setStatusCode(HttpStatus.UNAUTHORIZED);
              return response.setComplete();
        }
//        解析token中的内容payload
          Claims claimsBody = AppJwtUtil.getClaimsBody(token);
//        校验claimBody
           int i=AppJwtUtil.verifyToken(claimsBody);
           if (i==-1||i==0){
//                //            合法，则向header中重新设置userId
              Integer id=(Integer)claimsBody.get("id");
              log.info("find userid:{} from uri:{}",id,request.getURI());
               //            重新设置token到header中
                ServerHttpRequest serverHttpRequest=request.mutate().headers(httpHeaders -> {
                    httpHeaders.add("userId",id+"");
                }).build();
               //            重新构建请求头信息
               exchange.mutate().request(serverHttpRequest).build();
            }
        } catch (Exception exception) {
           exception.printStackTrace();
//           想客户断返回错误提示信息
          response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
       }
       return chain.filter(exchange);
    }

   @Override
    public int getOrder() {
       return 0;
   }
}
